<?php


namespace app\api\controller\v35;


use app\api\controller\v13\Auth2;
use app\common\cachemodel\ZhunleActivity;
use app\common\lib\exception\ApiException;
use app\common\model\User;
use app\common\model\ZhunleCourse;
use app\common\model\ZhunleCourseComment;
use app\common\model\ZhunleCourseCommentReply;
use app\common\model\ZhunleCourseCommentSupport;
use app\common\model\ZhunleCourseSection;
use app\common\model\ZhunleCourseSectionExercise;
use app\common\model\ZhunleCourseSectionInfo;
use app\common\model\ZhunleCourseSectionPlay;
use app\common\model\ZhunleCourseSectionProgress;
use app\common\model\ZhunleSectionExerciseProgress;
use Exception;
use think\Log;
use think\response\Json;

class VideoForTeach extends Auth2
{

    /**
     * 教学视频广场相关接口
     * @return Json
     * @throws Exception
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $page = input('param.page/d', 1);

        $CourseModel = new ZhunleCourse();
        $OrdersCacheModel = new \app\common\cachemodel\Orders();
        $CourseCommentModel = new ZhunleCourseComment();
        //获取所有课程基本信息
        $course = $CourseModel->getAllCourseInfo(['page' => $page]);

        // 由于要苹果审核不能添加sku所以这里判断下如果是ios1.9.2版本只显示一个零基础的课程
        $applePayGoodsConfig = config('apple_pay_goods');
        if ($this->headers['version'] === $applePayGoodsConfig['version'] && $applePayGoodsConfig['switch'] && $this->headers['app-type'] === 'ios')
        {
            $tmpData = [];
            foreach ($course['data'] as $d)
            {
                // 零基础课程
                if ((int)$d['id'] === 40)
                {
                    $tmpData[] = $d;
                }
            }
            $course['data'] = $tmpData;
        }
        //由于要苹果审核不能添加sku所以这里判断下如果是ios1.9.2版本只显示一个零基础的课程

        $timeLimitCourse = [];//限时课程
        $tmpCourse = [];//非限时课程
        if ($course && $course['data'])
        {
            foreach ($course['data'] as $k => $value)
            {
                $value['unlock_status'] = 0;
                //获取课程的购买人数
                $people_for_pay = $OrdersCacheModel->getTotalPrepaidOrder(6, $value['gid']) + $value['base_num'];

                if (!$people_for_pay)
                {
                    $people_for_pay = 0;
                }

                if ($course === false)
                {
                    // 若未查询到数据，则返回错误信息
                    return show(config('code.error'), $CourseModel->getError());
                }

                //将阿拉伯数字转换百千万单位
                $b = 10000;

                if ($people_for_pay > $b)
                {
                    $value['people_for_pay'] = floor($people_for_pay / $b) . 'w+';
                } else
                {
                    $value['people_for_pay'] = $people_for_pay;
                }

                //获取当前课程的平均评论分数
                $CourseCommentScore = $CourseCommentModel->getCourseCommentScore(['id' => $value['id']]);

                $all_score = 0;
                if ($CourseCommentScore)
                {
                    $all_score = array_sum(array_map(function ($val)
                    {
                        return $val['score'];
                    }, $CourseCommentScore));

                    $value['score_for_comment'] = round($all_score / count($CourseCommentScore), 1);

                } else
                {
                    $value['score_for_comment'] = 0;
                }

                if ($value['base_num'])
                {
                    $base_score = 5 * $value['base_num'];

                    $score = $all_score + $base_score;
                    $num = count($CourseCommentScore) + $value['base_num'];

                    $value['score_for_comment'] = round($score / $num, 1);

                }

                //判断是否是applePay
                $value['or_price'] = 0;
                $value['now_price'] = 0;
                $apgids = [];
                if ($this->is_apple_pay)
                {
                    foreach ($this->apple_goods['video_goods'] as $ap)
                    {
                        $apgids[] = $ap['id'];
                    }

                    if ($apgids && in_array($course['data'][$k]['gid'], $apgids))
                    {
                        $value['or_price'] = $ap['or_prize'];
                        $value['now_price'] = $ap['now_prize'];
                    }

                } else
                {
                    //获取活动折扣
                    $activeDiscount = active($course['data'][$k]['gid']);
                    //获取新版本活动信息
                    $new_activating = (new ZhunleActivity())->getActivingGood(6, $value['gid']);
                    if ($new_activating && !$this->is_apple_pay)
                    {
                        $value['now_price'] = sprintf('%.2f', $value['now_prize'] * $new_activating['attr']);
                    } elseif ($activeDiscount['discount'] && !$this->is_apple_pay)
                    {
                        $value['now_price'] = sprintf('%.2f', $value['now_prize'] * $activeDiscount['discount']);
                    } else
                    {
                        $value['now_price'] = sprintf('%.2f', $value['now_prize']);
                    }
                    $value['or_price'] = sprintf('%.2f', $value['or_prize']);
                }

                if ($this->headers['app-type'] === 'android')
                {
                    $value['or_price'] = $value['or_price'] === $value['now_price'] ? '' : $value['or_price'];
                }
                //获取课程解锁状态
                if ($this->user)
                {
                    $unlock_id = \app\common\cachemodel\ZhunleCourse::getVideoUnlockStatus($this->user['id'], $value['gid']);
                } else
                {
                    $unlock_id = [
                        'status' => false,
                        'gids' => []
                    ];
                }
                $value['is_time_limit'] = 0;
                if ($unlock_id['status'] === true)
                {
                    $value['unlock_status'] = 1;
                } else
                {
                    //判断课程是否是限时免费
                    $timeLimit = $CourseModel->getCourseTimeLimit($value['id']);
                    if ($timeLimit)
                    {
                        $value['is_time_limit'] = 1;
                        $timeLimitCourse[$k] = $value;
                    }
                }
                if (empty($timeLimit))
                {
                    $tmpCourse[] = $value;
                }
            }
        } else
        {
            $course = null;
        }
        $course['data'] = array_merge($timeLimitCourse, $tmpCourse);
        return show(config('code.success'), '加载成功', $course);
    }

    /**
     * 课程详情
     * @return Json
     * @throws Exception
     */
    public function course_detail()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $id = input('param.id/d');//课程id

        if (!$id || $id == 0)
        {
            return show(config('code.error'), '请确认当前查看的视频是否上架');
        }

        $uid = $this->user['id'] ?? null;

        // 模型引用
        $OrdersCacheModel = new \app\common\cachemodel\Orders();
        $CourseModel = new ZhunleCourse();
        $CourseCommentModel = new ZhunleCourseComment();
        $CourseSectionModel = new ZhunleCourseSection();
        $CourseSectionProgressModel = new ZhunleCourseSectionProgress();
        $CourseSectionPlayModel = new ZhunleCourseSectionPlay();
        $CourseSectionInfoModel = new ZhunleCourseSectionInfo();
        $SectionExerciseModel = new ZhunleCourseSectionExercise();
        $SectionExerciseProgress = new ZhunleSectionExerciseProgress();

        // 记录用户浏览次数
        if (isset($CourseSectionInfoModel) && $uid)
        {
            $CourseSectionInfoModel->save_section_info(['uid' => $uid, 'cid' => $id]);
        }

        // 获取课程的基本信息
        $course = $CourseModel->getCourseInfo(['id' => $id]);
        if ($course === false)
        {
            return show(config('code.error'), $CourseModel->getError());
        }
        //获取课程解锁状态
        if ($uid)
        {
            $unlock_status = \app\common\cachemodel\ZhunleCourse::getVideoUnlockStatus($uid, $course['gid']);
        } else
        {
            $unlock_status = [
                'status' => false,
                'gids' => []
            ];
        }
        // 获取课程的详情介绍
        $introduction = $CourseModel->getCourseIntroduction(['id' => $id]);

        if ($introduction === false)
        {
            $introduction['introduction'] = '';
        }

        // 获取当前课程的评论分数
        $CourseCommentScore = $CourseCommentModel->getCourseCommentScore(['id' => $id]);

        // 计算当前课程的平均评论分数
        if ($CourseCommentScore)
        {
            $all_score = array_sum(array_map(function ($val)
            {
                return $val['score'];
            }, $CourseCommentScore));

            $score_for_comment = round($all_score / count($CourseCommentScore), 1);
        } else
        {
            $score_for_comment = 0;
        }

        // 获取课程的购买人数
        $people_for_pay = $OrdersCacheModel->getTotalPrepaidOrder(6, $course['gid']) + $course['base_num'];

        if (!$people_for_pay)
        {
            $people_for_pay = 0;
        }

        // 获取当前课程的所有章节信息
        $section = $CourseSectionModel->getCourseSection(['id' => $course['id']]);
        if ($section === false)
        {
            return show(config('code.error'), $CourseSectionModel->getError());
        }

        $array = [
            'video_thumb' => $course['video_thumb'],//课程封面图
            'unlock_status' => 0,//课程解锁状态
        ];

        $array['time_limit_des'] = '';
        // 判断用户是否解锁了当前课程
        if ($unlock_status['status'] === true)
        {
            $array['unlock_status'] = 1;
        } else
        {
            //判断课程是否是限时免费
            $timeLimit = $CourseModel->getCourseTimeLimit($id);
            if ($timeLimit)
            {
                $array['time_limit_des'] = $timeLimit['des'];
                $array['unlock_status'] = 1;
            }
        }

        // 默认课程无试听图标
        $is_audition = 0;
        $array['play_video_id'] = '';

        $csid = 0;
        // 获取用户的所有播放记录
        if ($uid)
        {
            $CoursePlay = $CourseSectionPlayModel->getPlayId(['uid' => $uid]);
        } else
        {
            $CoursePlay = [];
        }

        foreach ($CoursePlay as $item)
        {
            if ($item['cid'] == $id)
            {
                $csid = $item['is_last_csid'];
            }
        }

        foreach ($section as $k => $s)
        {
            // 获取当前用户当前章节最新进度
            if ($uid)
            {
                $SectionProgress = $CourseSectionProgressModel->getSectionProgressInfo(['id' => $s['id'], 'uid' => $uid]);
            } else
            {
                $SectionProgress = [];
            }
            //获取当前章节是否有习题
            $SectionExercise = $SectionExerciseModel->getSectionExercise($s['id']);
            $SectionExercise = json_decode($SectionExercise, true);
            if (!empty($SectionExercise))
            {
                // 过滤不完整的习题 （没有题目、选项A、B、C、D、答案、解析  则视为该问题不完整）
                // 初始化 定义完整的习题
                $temp = [];
                foreach ($SectionExercise as $item)
                {
                    if ($item['title'] && $item['optionA'] && $item['optionB'] && $item['optionC'] && $item['optionD'] && $item['answer'] && $item['analysis'])
                    {
                        $temp[] = $item;
                    }
                }
                if (!empty($temp))
                {
                    $section[$k]['is_have_exercise'] = 1;
                } else
                {
                    $section[$k]['is_have_exercise'] = 0;
                }
            } else
            {
                $section[$k]['is_have_exercise'] = 0;
            }
            if ($SectionProgress)
            {
                $section[$k]['progress'] = $SectionProgress['recent_progress']; //5.
            } else
            {
                $section[$k]['progress'] = 0;
            }

            // 获取用户的播放记录
            if ($s['id'] == $csid)
            {
                $array['play_video_id'] = $section[$k]['vid'];
            }

            // 若用户未播放过并且该视频试听切默认播放则返给前端
            if ($array['play_video_id'] == '' && $s['is_play'] == 1)
            {
                $array['play_video_id'] = $section[$k]['vid'];
            }

            //获取用户当前章节的习题进度
            if ($uid)
            {
                $exercise = $SectionExerciseProgress->getUserExerciseProgress(['uid' => $uid, 'csid' => $s['id']]);
            } else
            {
                $exercise = [];
            }
            //默认练习进度为视频未看完状态
            if ($uid)
            {
                if (empty($exercise))
                {
                    $SectionExerciseProgress->addExerciseProgress(['uid' => $uid, 'csid' => $s['id'], 'status' => 0]);
                    $exercise[0] = 0;
                } //修改习题状态为待练习
                elseif ($exercise[0] == 0 && isset($SectionProgress['total_progress']) && $SectionProgress['total_progress'] >= $s['video_duration'])
                {
                    $SectionExerciseProgress->editExerciseProgress(['uid' => $uid, 'csid' => $s['id'], 'status' => 1]);
                    $exercise[0] = 1;
                }

                $section[$k]['exercise_status'] = $exercise[0];
            } else
            {
                $section[$k]['exercise_status'] = 0;
            }

            $section[$k]['video_id'] = $section[$k]['vid'];
            unset($section[$k]['vid'], $section[$k]['is_play']);
            // 若有章节试听,则课程有试听图标
            if ($s['is_audition'])
            {
                $is_audition = 1;
            }

        }

        //将阿拉伯数字转换百千万单位
        $b = 10000;

        if ($people_for_pay > $b)
        {
            $people_for_pay = floor($people_for_pay / $b) . 'w+';
        }

        //判断是否是applePay
        $or_price = 0;
        $now_price = 0;
        $aids = [];
        if ($this->is_apple_pay)
        {
            foreach ($this->apple_goods['video_goods'] as $ap)
            {
                $aids[] = $ap['id'];
            }

            if ($aids && in_array($course['gid'], $aids))
            {
                $or_price = $ap['or_prize'];
                $now_price = $ap['now_prize'];
            }

        } else
        {
            //获取活动折扣
            $activeDiscount = active($course['gid']);
            //获取新版本活动信息
            $new_activating = (new ZhunleActivity())->getActivingGood(6, $course['gid']);
            if ($new_activating && !$this->is_apple_pay)
            {
                $now_price = sprintf('%.2f', $course['now_prize'] * $new_activating['attr']);
            } elseif ($activeDiscount['discount'] && !$this->is_apple_pay)
            {
                $now_price = sprintf('%.2f', $course['now_prize'] * $activeDiscount['discount']);
            } else
            {
                $now_price = sprintf('%.2f', $course['now_prize']);
            }
            $or_price = sprintf('%.2f', $course['or_prize']);
        }

        // 课程信息
        $array['introduction_info'] = [
            'or_price' => $or_price,
            'now_price' => $now_price,
            'gid' => (int)$course['gid'],
            'thumb' => $course['thumb'],
            'title' => $course['title'],
            'description' => $course['description'],
            'score_for_comment' => $score_for_comment,
            'people_for_pay' => $people_for_pay,
            'introduction_for_course' => $introduction['introduction'],
            'is_audition' => $is_audition,
            'uen' => $this->user['uen'] ?? null,
            'is_show_discount' => 1
        ];

        // 获取课程章节信息
        $array['course_info'] = $section;

        return show(config('code.success'), '加载成功', $array);
    }

    /**
     * 课程评价详情
     * @return Json
     * @throws Exception
     */
    public function course_comment()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $id = input('param.id/d', 0);//课程id
        $page = input('param.page/d', 1);
        $uid = $this->user['id'] ?? null;

        if (!$id || $id == 0)
        {
            return show(config('code.error'), '请确认当前查看的视频是否上架');
        }

        // 模型引用
        $UserModel = new User();
        $CourseModel = new ZhunleCourse();
        $CourseCommentModel = new ZhunleCourseComment();
        $CourseCommentSupportModel = new ZhunleCourseCommentSupport();
        $CourseCommentReplyModel = new ZhunleCourseCommentReply();

        // 获取当前课程的信息
        $course = $CourseModel->getCourseInfo(['id' => $id]);
        if ($course === false)
        {
            return show(config('code.error'), $CourseModel->getError());
        }

        //获取课程解锁状态
        $unlock = \app\common\cachemodel\ZhunleCourse::getVideoUnlockStatus($this->user['id'], $course['gid']);

        $unlock_status = 0;
        // 判断当前用户是否解锁了当前课程
        if ($unlock['status'] === true)
        {
            $unlock_status = 1;
        } else
        {
            $timeLimit = $CourseModel->getCourseTimeLimit($id);
            if ($timeLimit)
            {
                $unlock_status = 1;
            }
        }
        // 获取当前用户的所有评论信息
        if ($uid)
        {
            $user_comment = $CourseCommentModel->getUserCommentInfo(['uid' => $uid]);
        } else
        {
            $user_comment = [];
        }

        $my_comment = null;

        if ($user_comment)
        {
            foreach ($user_comment as $k => $c)
            {
                if ($c['cid'] == $id)
                {
                    $my_comment = [
                        'id' => $c['id'],
                        'score' => $c['score'],
                    ];

                    if ($c['status'] == 1)
                    {
                        $my_comment['status'] = 0;
                        $my_comment['tips_content'] = '违规评论，禁止编辑';

                    } else
                    {
                        $my_comment['status'] = 1;
                        $my_comment['tips_content'] = $c['content'];
                    }

                }
            }
        }
        // 获取当前课程的评论信息
        $comment = $CourseCommentModel->getCourseComment(['id' => $id, 'page' => $page]);

        if ($comment)
        {
            // 获取当前评论的踩或赞的数量
            foreach ($comment['data'] as $k => $datum)
            {
                if ($uid && $datum['uid'] == $uid)
                {
                    $comment['data'][$k]['is_self'] = 1;
                } else
                {
                    $comment['data'][$k]['is_self'] = 0;
                }
                // 获取当前用户的信息
                try
                {
                    $UserInfo = $UserModel->getUserinfo(['id' => $datum['uid']]);
                }
                catch (ApiException $e)
                {
                    unset($comment['data'][$k]);
                    continue;
                }
                catch (Exception $e)
                {
                    Log::write('course_comment:' . $e->getMessage(), 'error');
                    unset($comment['data'][$k]);
                    continue;
                }
                if ($UserInfo)
                {
                    $comment['data'][$k]['name'] = $UserInfo['nickname'];
                    $comment['data'][$k]['avatar'] = $UserInfo['avatar'];
                    $comment['data'][$k]['create_time'] = date('Y-m-d', $datum['create_time']);
                    // 获取踩的所有用户
                    $bad = $CourseCommentSupportModel->getCourseCommentBadOrGood(['id' => $datum['id'], 'type' => 1]);
                    // 获取赞的数量
                    $good = $CourseCommentSupportModel->getCourseCommentBadOrGood(['id' => $datum['id'], 'type' => 2]);

                    if ($bad === false || $good === false)
                    {
                        return show(config('code.error'), $CourseCommentSupportModel->getError());
                    }

                    // 重组评论的踩赞
                    $comment['data'][$k]['bad']['num'] = count($bad);
                    $comment['data'][$k]['good']['num'] = count($good);
                    // 判断当前用户是否踩了当前评论
                    if ($uid && in_array($uid, $bad))
                    {
                        $comment['data'][$k]['bad']['status'] = 1;
                    } else
                    {
                        $comment['data'][$k]['bad']['status'] = 0;
                    }

                    // 判断当前用户是否赞了当前评论
                    if ($uid && in_array($uid, $good))
                    {
                        $comment['data'][$k]['good']['status'] = 1;
                    } else
                    {
                        $comment['data'][$k]['good']['status'] = 0;
                    }

                    // 获取当前评论的回复
                    $reply = $CourseCommentReplyModel->getCommentReply(['id' => $datum['id']]);

                    $comment['data'][$k]['reply_list'] = $reply;

                    if (!$comment['data'][$k]['content'])
                    {
                        $comment['data'][$k]['content'] = '此用户没有填写评价';
                    }

                    unset($comment['data'][$k]['uid'], $comment['data'][$k]['status'], $comment['data'][$k]['cid']);
                }
            }

            $comment['data'] = array_values($comment['data']);

        } else
        {
            $comment = null;
        }

        // 获取当前课程的评论分数
        $CourseCommentScore = $CourseCommentModel->getCourseCommentScore(['id' => $id]);

        // 计算当前课程的平均评论分数
        if ($CourseCommentScore)
        {
            $all_score = array_sum(array_map(function ($val)
            {
                return $val['score'];
            }, $CourseCommentScore));

            $score_for_comment = round($all_score / count($CourseCommentScore), 1);
        } else
        {
            $score_for_comment = 0;
        }

        $data = [
            'course_info' => [
                'unlock_status' => $unlock_status,
                'is_time_limit' => !empty($timeLimit) ? 1 : 0,
                'score' => $score_for_comment,
                'people_for_comment' => count($CourseCommentScore),
                'my_comment' => $my_comment
            ],
            'comment_info' => $comment
        ];

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 保存当前用户的播放记录和进度和练习状态
     * @return \think\response\Json
     */
    public function save_section_progress()
    {
        $param = request()->param();

        if (!$this->user)
        {
            return show(config('code.success'), '保存成功');
        }

        $validate = validate('VideoForTeach');

        if ($validate->scene('save_section_progress')->check($param) !== true)
        {
            return show(config('code.error'), $validate->getError());
        }

        $cid = $param['cid'];
        $csid = $param['csid'];// 课程章节id
        $progress = $param['progress'];// 章节进度
        $uid = $this->user['id'];

        $SectionProgressModel = new ZhunleCourseSectionProgress();
        $SectionPlayModel = new ZhunleCourseSectionPlay();
        $SectionModel = new ZhunleCourseSection();
        $SectionExerciseProgressModel = new ZhunleSectionExerciseProgress();

        // 获取当前章节信息
        $Section = $SectionModel->getSectionInfo(['csid' => $csid]);
        //获取用户当前章节进度信息
        $SectionProgress = $SectionProgressModel->getSectionProgressInfo(['id' => $csid, 'uid' => $uid]);

        if ($Section === false)
        {
            return show(config('code.error'), $SectionModel->getError());
        }

        // 预防客户端传错参数
        if ($progress > $Section['video_duration'])
        {
            $progress = $Section['video_duration'];
        }
        // 保存当前课程章节播放进度
        if ($progress > 0)
        {
            $progress_status = $SectionProgressModel->saveProgress(['uid' => $uid, 'csid' => $csid, 'progress' => $progress]);
        }
        if ($progress_status === false)
        {
            return show(config('code.error'), $SectionProgressModel->getError());
        } else
        {
            // 更新当前用户播放进度缓存
            $SectionProgressModel->rm_cache(['uid' => $uid, 'csid' => $csid]);
        }
        // 保存当前用户最后播放的章节信息
        $play = $SectionPlayModel->savePlayId(['cid' => $cid, 'uid' => $uid, 'csid' => $csid]);
        if ($play === false)
        {
            return show(config('code.error'), $SectionPlayModel->getError());
        } else
        {
            $SectionPlayModel->rm_cache(['uid' => $uid, 'cid' => $cid]);
        }

        //若当前未保存过进度,则将当前进度保存
        if (empty($SectionProgress))
        {
            $SectionProgress['total_progress'] = $progress;
        }

        //获取用户当前章节习题进度
        $exercise_progress = $SectionExerciseProgressModel->getUserExerciseProgress(['uid' => $uid, 'csid' => $csid]);
        //默认练习进度为视频未看完状态
        if (empty($exercise_progress))
        {
            $SectionExerciseProgressModel->addExerciseProgress(['uid' => $uid, 'csid' => $csid, 'status' => 0]);
        } //修改习题状态为待练习
        elseif ($exercise_progress[0] == 0 && $SectionProgress['total_progress'] >= $Section['video_duration'])
        {
            $SectionExerciseProgressModel->editExerciseProgress(['uid' => $uid, 'csid' => $csid, 'status' => 1]);
        }

        return show(config('code.success'), '保存成功');
    }
}
